package com.berwin.bmfb.views;

import com.berwin.bmfb.entity.BMFont;
import com.berwin.bmfb.utility.UserDefault;
import com.berwin.bmfb.views.layout.VerticalFlowLayout;
import com.sun.xml.internal.rngom.parse.host.Base;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class BaseConfigView extends BasePanel {

    private BMFont bmFont = null;

    private JTextField tfFileName = null;
    private JTextField tfFontName = null;
    private JTextField tfTextureName = null;
    private JSpinner spCharSpace = null;
    private JSpinner spCharHeight = null;
    //    private JSpinner spEmptyWidth = null;
    private JSpinner spPadding = null;
    private JSpinner spBaseline = null;

    public BaseConfigView(MainView mainView, BMFont bmFont) {
        super(mainView);
        this.bmFont = bmFont;
//        this.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP));

//        this.setLayout(new GridLayout(2, 1));

        String names[] = {"文件路径:", "字体名称:", "图集名称:", "字符间距:", "字体高度:", "Padding:", "对齐基线:"};
        String tips[] = {"保存文件的路径:", "名称由文件路径决定:", "图集名称由文件路径决定:", "字符间距:", "字体的高度(可以填写最高字符高度):", "Padding:", "Baseline:"};
        int tfDefColumns = 8;
        this.setLayout(new GridLayout(names.length, 1));


        JPanel pnlFileBrowser = new JPanel();
        pnlFileBrowser.setLayout(new BorderLayout());

        this.tfFileName = new JTextField(tfDefColumns);
        pnlFileBrowser.add(this.tfFileName, BorderLayout.CENTER);

        JButton btnBrowser = new JButton("浏览");
        pnlFileBrowser.add(btnBrowser, BorderLayout.EAST);
        btnBrowser.addActionListener(e -> {
            // 选择fnt文件
            String defFilePath = UserDefault.getInstance().getValueForKey(MainView.KEY_LAST_FILE, this.bmFont.getFilePath());
            JFileChooser fileChooser = new JFileChooser(defFilePath);
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.getAbsolutePath().endsWith(".fnt");
                }

                @Override
                public String getDescription() {
                    return "fnt格式文件";
                }
            });
            fileChooser.setSelectedFile(new File(defFilePath));
            int i = fileChooser.showSaveDialog(this.mainView);
            if (i == JFileChooser.APPROVE_OPTION) {
                File selFile = fileChooser.getSelectedFile();
                String file = selFile.getAbsolutePath();
                if (!file.endsWith(".fnt")) {
                    file += ".fnt";
                }
                UserDefault.getInstance().setValueForKey(MainView.KEY_LAST_FILE, file);
                // 处理
                int idx = file.lastIndexOf(File.separator);
                int idxP = file.lastIndexOf(".");
                idxP = idxP == -1 ? file.length() : idxP;
                String name = file.substring(idx + 1, idxP);
                bmFont.setFilePath(file);
                this.tfFileName.setText(file);
                this.tfFontName.setText(name);
                this.tfTextureName.setName(name + ".png");
            }
        });

        this.tfFontName = new JTextField(tfDefColumns);
        this.tfFontName.setEditable(false);
        this.tfFontName.setHorizontalAlignment(JTextField.RIGHT);

        this.tfTextureName = new JTextField(tfDefColumns);
        this.tfTextureName.setEditable(false);
        this.tfTextureName.setHorizontalAlignment(JTextField.RIGHT);

        SpinnerModel model1 = new SpinnerNumberModel(this.bmFont.getEditorExtSpacing(), -1000, 1000, 1);
        this.spCharSpace = new JSpinner(model1);

        SpinnerModel model2 = new SpinnerNumberModel(this.bmFont.getLineHeight(), -1000, 1000, 1);
        this.spCharHeight = new JSpinner(model2);

//        SpinnerModel model3 = new SpinnerNumberModel(this.bmFont.getEmptyBMChar().getxAdvance(), -1000, 1000, 1);
//        this.spEmptyWidth = new JSpinner(model3);

        SpinnerModel model4 = new SpinnerNumberModel(this.bmFont.getPadding(), -1000, 1000, 1);
        this.spPadding = new JSpinner(model4);

        SpinnerModel model5 = new SpinnerNumberModel(this.bmFont.getBaseline(), -1000, 1000, 1);
        this.spBaseline = new JSpinner(model5);


        JComponent components[] = {
                pnlFileBrowser,
                this.tfFontName,
                this.tfTextureName,
                this.spCharSpace,
                this.spCharHeight,
//                this.spEmptyWidth,
                this.spPadding,
                this.spBaseline,
        };

        for (int i = 0; i < components.length; i++) {
            JPanel pnlRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JLabel lbl = new JLabel(names[i]);
            lbl.setToolTipText(tips[i]);
            pnlRow.add(lbl);
            pnlRow.add(components[i]);
            this.add(pnlRow);
        }

        this.tfFontName.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
//                String pageFile = String.format("%s.png", BaseConfigView.this.tfFontName.getText());
//                BaseConfigView.this.tfTextureName.setText(pageFile);
//                BaseConfigView.this.onValueChanged();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
//                String pageFile = String.format("%s.png", BaseConfigView.this.tfFontName.getText());
//                BaseConfigView.this.tfTextureName.setText(pageFile);
//                BaseConfigView.this.onValueChanged();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
//                String pageFile = String.format("%s.png", BaseConfigView.this.tfFontName.getText());
//                BaseConfigView.this.tfTextureName.setText(pageFile);
//                BaseConfigView.this.onValueChanged();

            }
        });
        this.tfTextureName.getDocument().addDocumentListener(this);
        this.spCharSpace.addChangeListener(this);
        this.spCharHeight.addChangeListener(this);
//        this.spEmptyWidth.addChangeListener(this);
        this.spPadding.addChangeListener(this);
        this.spBaseline.addChangeListener(this);

        this.onBMFontUpdated(this.bmFont);
    }

    @Override
    public void onUpdate() {
//        this.tfFontName.setText(this.bmFont.getFace());
//        this.tfTextureName.setText(this.bmFont.getPageFile());
//        this.spCharSpace.setValue(this.bmFont.getEditorExtSpacing());
//
//        this.spCharHeight.setValue(this.bmFont.getLineHeight());
//        this.spEmptyWidth.setValue(this.bmFont.getEmptyWidth());
//        this.spPadding.setValue(this.bmFont.getPadding());
//        this.spBaseline.setValue(this.bmFont.getBaseline());

    }

    @Override
    public void onSelectLetter(int idx) {
        this.isFromSelected = true;
        this.giveUpListenValueChange = true;
        this.isFromSelected = false;
        this.giveUpListenValueChange = false;
        this.onValueChanged();
    }

    @Override
    public void onValueChanged() {
        this.bmFont.setFace(this.tfFontName.getText());
        this.bmFont.setPageFile(this.tfTextureName.getText());
        this.bmFont.setEditorExtSpacing((Integer) this.spCharSpace.getValue());

        this.bmFont.setLineHeight((Integer) this.spCharHeight.getValue());
        int oldPadding = this.bmFont.getPadding();
        this.bmFont.setPadding((Integer) this.spPadding.getValue());
        this.bmFont.setBaseline((Integer) this.spBaseline.getValue());

        this.mainView.handleUpdate();
        if (oldPadding != this.bmFont.getPadding())
            this.mainView.handleDoLayoutChars();
    }

    @Override
    public void onBMFontUpdated(BMFont bmFont) {
        this.bmFont = bmFont;

        this.giveUpListenValueChange = true;
        this.tfFontName.setText(this.bmFont.getFace());
        this.tfTextureName.setText(this.bmFont.getPageFile());

        this.spCharSpace.setValue(this.bmFont.getEditorExtSpacing());
        this.spCharHeight.setValue(this.bmFont.getLineHeight());
        this.spPadding.setValue(this.bmFont.getPadding());
        this.spBaseline.setValue(this.bmFont.getBaseline());
        this.giveUpListenValueChange = false;
    }
}
